#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/07/18 11:27
# @Author : zengxiaolong
# @File    : get_all_case.py
import os
import csv
from utils import GetYamlData

default_path = os.path.join(os.path.abspath('..'), 'data')


def get_all_files(dir_path):
    file_list = []
    for root, dirs, files in os.walk(dir_path):
        for _file in files:
            file_list.append(os.path.join(root, _file))
    return file_list


def save_dict_as_csv(data, file_path):
    keys = data[0].keys()  # 获取字典的键作为CSV文件的列名

    with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=keys)
        writer.writeheader()  # 写入列名
        writer.writerows(data)  # 逐行写入数据


def collect_case_to_csv(file_path=default_path):
    """默认读取data目录下所有的用例，保存至csv，格式与钉钉自动化脚本登记一致"""
    folder_path = file_path
    files = get_all_files(folder_path)
    res = []
    files = tuple(filter(lambda x: x.endswith('.yaml'), files))
    for file in files:
        api_data = GetYamlData(file_dir=file).get_yaml_data()['case']
        if api_data:
            for i in api_data:
                res.append(
                    {'场景描述': i['name'], '进度': '100%', '接口地址': i['url'],
                     'yaml用例路径': file[file.find('zhcx-api-auto'):]})
    csv_file_path = 'output.csv'
    save_dict_as_csv(res, csv_file_path)
    print("CSV file saved.")


if __name__ == '__main__':
    folder_path = os.path.join(default_path, 'Aliexpress_Listing_Manage')
    collect_case_to_csv(folder_path)
